package github.leavesczy.reactivehttpsamples.ui.addbridge

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.StringUtils
import github.leavesczy.reactivehttpsamples.base.BaseFragment
import github.leavesczy.reactivehttpsamples.core.mode.BridgeRecordItem
import github.leavesczy.reactivehttpsamples.core.mode.MeasureModelData
import github.leavesczy.reactivehttpsamples.core.mode.MonitorAnalysisData
import github.leavesczy.reactivehttpsamples.core.viewmodel.addbridge.AddBridgeModel
import github.leavesczy.reactivehttpsamples.databinding.FragmentDataAnalysisModelBinding
import github.leavesczy.reactivehttpsamples.ui.addbridge.func.BridgeFunction
import github.leavesczy.reactivehttpsamples.util.BridgeDataHelper
import github.leavesczy.reactivehttpsamples.widget.dialog.BridgeSampleSelectDialog


class DataAnalysisModelBridge : BaseFragment(), BridgeFunction {
    companion object {
        fun newInstance(item: BridgeRecordItem?): Fragment {
            val fragment = DataAnalysisModelBridge()
            val bundle = Bundle()
            item?.let {
                bundle.putSerializable("item", it)
            }
            fragment.arguments = bundle
            return fragment
        }
    }

    private var bind: FragmentDataAnalysisModelBinding? = null

    private val mBind: FragmentDataAnalysisModelBinding get() = bind!!

    private val viewModel by getViewModel<AddBridgeModel> {
        bridgeMeasureBodyData.observe(viewLifecycleOwner) {
            if (it.bodyList.isEmpty()) {
                showToast("没有查询到样本数据")
            } else {
                showMeasureDialog(it.bodyList)
            }
        }
    }

    private fun showMeasureDialog(bodyList: List<MeasureModelData>) {
        BridgeSampleSelectDialog()
            .init(requireContext(), bodyList, sampleSelectIds, object : BridgeSampleSelectDialog.Callback {
                override fun cancel() {

                }

                override fun ok(ids: MutableList<Long>?) {
                    sampleSelectIds.clear()
                    sampleSelectIds.addAll(ids!!)
                    mBind.maTfMeasureSampleNumber.editTextStr=sampleSelectIds.size.toString()
                }
            })
            .show("BridgeSampleSelectDialog")
    }

    private var bridgeType: String? = null
    private var itemData: BridgeRecordItem? = null

    private val sampleSelectIds = mutableListOf<Long>()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        bind = FragmentDataAnalysisModelBinding.inflate(inflater, container, false)
        return mBind.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initListener()
        initRefresh()
        initData()
        initView()
    }


    private fun initView() {
        itemData?.let {
            val editable = it.isCanAnalysis() && !getForbiddenEdit(activity)
            val data = it.monitorAnalysis
            dealData(data, editable)
        }
    }

    private fun initData() {
        itemData = arguments?.getSerializable("item") as? BridgeRecordItem
        mBind.icCbSampleType.setItems(BridgeDataHelper.getSampleTypeList())
    }

    fun initListener() {
        mBind.icCbSampleType.setSelectCallback {
            //把测试样例对应的测试样本 初始化掉
            if(it.value.toInt()==itemData?.monitorAnalysis?.sampleType){
                resetSelectIds(itemData?.monitorAnalysis?.measurementSampleIds)
            }else{
                resetSelectIds(null)
            }
        }

        mBind.maTfMeasureSampleNumber.initButtonTextListener {
            //右侧点击事件,请求当前样本的列表，拿到数据后，再去显示弹框
            val  bridgeCode=getBridgeCode(activity)
            if(bridgeCode.isNullOrEmpty()){
                showToast("请先输入桥梁编码")
                return@initButtonTextListener
            }
            viewModel.requestBridgeMeasureList(bridgeCode,mBind.icCbSampleType.select.value)
        }

    }

    override fun onResume() {
        super.onResume()
        refreshBridgeType()
    }

    private fun initRefresh() {


    }


    override fun onDestroyView() {
        super.onDestroyView()
        bind = null
    }
    override fun refreshBridgeDetail(itemData: BridgeRecordItem) {
        this.itemData=itemData
        if(bind!=null){
            initView()
        }
    }

    override fun refreshBridgeType() {
        val bridgeType = (activity as? BridgeAddActivity)?.getBridgeType()
        if (bridgeType.isNullOrEmpty()) {
            return
        }
        if (!this.bridgeType.isNullOrEmpty() && this.bridgeType == bridgeType) {
            //不需要重复处理了
            return
        }
        this.bridgeType = bridgeType
        //根据桥梁类型判断 展示的字段
        when (bridgeType) {
            "1" -> {

            }

            "3" -> {

            }
        }
        initDefaultValue()
    }


    private fun initDefaultValue() {
        if (null != itemData) {
            return
        }

        val editable = true
        val data = MonitorAnalysisData(
            sensorSamplingFrequency = "100",
            measurementSampleNumber = "0",
            measurementSampleIds = "[]",
            sampleType = 0,
            epscCode = "32651",
            resultJson = ""
        )
        dealData(data, editable)
    }

    private fun dealData(data: MonitorAnalysisData, editable: Boolean) {
        dealSpinner(mBind.icCbSampleType, data.sampleType.toString(), editable)
        dealTextField(mBind.maTfSensorSamplingFrequency, data.sensorSamplingFrequency, editable)
        resetSelectIds(data.measurementSampleIds)
        mBind.maTfMeasureSampleNumber.setEditTextEnable(editable)
        dealTextField(mBind.maTfEpscCode, data.epscCode, editable)
    }

    private fun resetSelectIds(strIds:String?){
        sampleSelectIds.clear()
        if(!StringUtils.isEmpty(strIds)){
            sampleSelectIds.addAll(JSON.parseArray(strIds,Long::class.java))
        }
        mBind.maTfMeasureSampleNumber.editTextStr=sampleSelectIds.size.toString()
    }

    override fun dealRequestParam(mapParent: MutableMap<String, Any>) {
        val map = mutableMapOf<String, Any>()
        mapParent.put("monitorAnalysis", map)

        addSpinnerParam(map, mBind.icCbSampleType, "sampleType", "测试类型")
        addTextFieldParam(map, mBind.maTfSensorSamplingFrequency, "sensorSamplingFrequency", "采样频率")
        addTextButtonFieldParam(map, mBind.maTfMeasureSampleNumber, "measurementSampleNumber", "样本数量")
        map.put("measurementSampleIds", sampleSelectIds.toString())
        addTextFieldParam(map, mBind.maTfEpscCode, "epscCode", "桥梁EPSG代号")
    }

    override fun check() {
        checkSpinner(mBind.icCbSampleType, itemData?.monitorAnalysis?.sampleType.toString())
        checkText(mBind.maTfSensorSamplingFrequency,itemData?.monitorAnalysis?.sensorSamplingFrequency)
        //样本的校验需要特殊处理
        checkText(mBind.maTfEpscCode,itemData?.monitorAnalysis?.epscCode)

    }

}